package com.cn.transfer.handle.impl.saleorder;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.DocumentApproval;
import com.cn.transfer.common.entity.jiandaoyun.JdyPurchaseOrder;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.common.utils.exception.BizException;
import com.cn.transfer.common.vo.MessagePushVO;
import com.cn.transfer.handle.MessageStrategy;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import com.cn.transfer.mapper.VvSaSaleOrderBMapper;
import com.cn.transfer.mapper.VvSaSaleOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 向伟典
 * @date: 2023/9/14 11:04
 * @Description: 当销售订单弃审时
 */
@Slf4j
@Component
public class SaleOrderDeleteImpl implements MessageStrategy {
    @Autowired
    private VvSaSaleOrderMapper vvSaSaleOrderMapper;
    @Autowired
    private VvSaSaleOrderBMapper vvSaSaleOrderBMapper;

    @Transactional
    @Override
    public void handle(MessagePushVO message) {
        DocumentApproval documentApproval = ConnmeUtils.mapToObject(message.getBizContent(), DocumentApproval.class);

        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "6500165a60a971000ab0ad28");
        parameter.put("entry_id", "65015e41ddd8340007a1698d");
        List<JdyPurchaseOrder> jdyPurchaseOrders = PurchaseCommunity.queryBased(parameter, headers, documentApproval.getVoucherCode(),"documentnumber");
        if (jdyPurchaseOrders.size() == 0) {
            throw new BizException("目前没有查询到销售订单，无法删除");
        }
        // 执行删除操作
        Map<String, Object> parameterDelete = new HashMap<>();
        parameterDelete.put("app_id", "6500165a60a971000ab0ad28");
        parameterDelete.put("entry_id", "65015e41ddd8340007a1698d");
        parameterDelete.put("data_id", jdyPurchaseOrders.get(0).get_id());
        String jsonSaleDelete = JSONUtil.toJsonStr(parameterDelete);
        vvSaSaleOrderMapper.deleteSaleOrderId(documentApproval.getVoucherID());
        vvSaSaleOrderBMapper.deleteSaleOrderBDTO(documentApproval.getVoucherID());
        JSONObject jdySaledelete = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/delete", headers, jsonSaleDelete);
        log.info("销售订单弃审时删除简道云数据：====" + jdySaledelete);
    }

    @Override
    public String getMsgType() {
        return "SaleOrder_UnAudit";
    }
}
